﻿'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('=== testUserQuery 开始 ===');
  console.log('1. 接收参数:', event);
  
  try {
    const { userId } = event;
    
    if (!userId) {
      return {
        code: 400,
        msg: '用户ID缺失'
      };
    }
    
    console.log('2. 查询用户信息，userId:', userId);
    
    // 查询用户信息
    const userRes = await db.collection('uni-id-users')
      .doc(userId)
      .field({ nickname: true, avatar_file: true })
      .get();
    
    console.log('3. 查询结果:', userRes);
    
    if (!userRes.data || userRes.data.length === 0) {
      return {
        code: 404,
        msg: '用户不存在',
        data: { userId, queryResult: userRes }
      };
    }
    
    const userData = userRes.data[0];
    console.log('4. 用户数据:', userData);
    
    return {
      code: 200,
      msg: '查询成功',
      data: {
        userId: userId,
        nickname: userData.nickname,
        avatar: userData.avatar_file?.url || '/static/images/default-avatar.png',
        rawData: userData
      }
    };
    
  } catch (error) {
    console.error(' testUserQuery 异常:', error);
    return {
      code: 500,
      msg: '查询失败: ' + error.message,
      error: error
    };
  }
};
